import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Park } from './park';
import 'rxjs/add/observable/forkJoin'
import { UserSettingProvider } from '../user-setting/user-setting';
import { SQLite } from '@ionic-native/sqlite';
import { SqliteHelperProvider } from '../sqlite-helper/sqlite-helper';
import { Form } from 'ionic-angular';
/*
  Generated class for the ParkDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ParkDataProvider {
  private readonly baseUrl: string = 'https://api2.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders({
    'X-Bmob-Application-Id':'1170ab838f3d5a667723eb4929a4548d',
    'X-Bmob-REST-API-Key':'632dcbaffdd164e0433d7a98b8059d63',
    'Content-Type': 'application/json'
  
});
  constructor(public http: HttpClient,
    private userSettingProvider:UserSettingProvider,
    private sqliteHelperProvider:SqliteHelperProvider) {
    console.log('Hello ParkDataProvider Provider');
  }

  getParks(num : number, page: number): Observable<Park[]>{
    let _params = new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${ (page - 1)*num}`);
    return this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
            {headers:this.httpHeaders,params:_params})
            .map(_=>_['results']);
  }

    /**
   * 获取记录一条数
   */
  getCount():Observable<number>{
    return this.http.get<number>(`${this.baseUrl}/classes/parks?
    limit=0&count=1`,{headers: this.httpHeaders}).map(data=>data['count']);
  }

  getPark(objectId:string):Observable<Park>{
    return this.http.get<Park>(`${this.baseUrl}/classes/parks/${objectId}`,
    {headers:this.httpHeaders});
  }

  /**
   * 获取所有记录
   * @param total 
   */
  getAllParks(total:number):Observable<Park[][]>{
    let num = 500;
    let all:Observable<Park[]>[]=[];
    for (let index = 0; index <total/num; index++) {
      let _params = new HttpParams()
      .set('limit',`${num}`)
      .set('skip',`${ index*num}`);
      all[index] = this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
      {headers:this.httpHeaders,params:_params})
      .map(_=>_['results']); 
    }
    return Observable.forkJoin(all);//连续执行这个操作来连接
  }

  /**
   * 缓存HTTP数据到本地
   */
  setParksToCache():Promise<any>{
    return new Promise<any>((resolve,reject)=>{
      this.userSettingProvider.isRefreshData()
      .then(isRefresh=>{
        console.log(`是否刷新：${isRefresh}`);
        if(isRefresh){
          this.sqliteHelperProvider.createOrOpenDb() //打开或新建数据库
          .then(()=>{
            //清空原有数据路中的数据，即清空缓存
            return this.sqliteHelperProvider.executeSql('DELETE FROM parks_lite',[]);
          })
          .then(()=>{
            return this.getCount().toPromise();//获取远端数据记录数
          })
          .then(total=>{
            return this.getAllParks(total).toPromise();//获取远端记录
          })
          .then(data=>{
            data.forEach(parks =>{
              console.log(`待加入数据：${parks.length}`);

              let sql = 'INSERT INTO parks_lite (objectId,name,point)';
              sql += ` SELECT '${parks[0].objectId}', '${parks[0].name}', '${parks[0].point}'`;
              for(let i=1; i<parks.length;i++){
                sql += `UNION ALL SELECT '${parks[i].objectId}', '${parks[i].name}', '${parks[i].point}'`;    
              }

              this.sqliteHelperProvider.executeSql(sql,[]);

            });//插入数据到数据库中，即建立缓存
          //   data.forEach(parks =>{
          //     parks.forEach(park=>{
          //       let sql = 'INSERT INTO parks_lite (objectId,name,point) VALUES(?,?,?)';//实际要做4W+次插入操作，效率低
          //       let sql_params = [park.objectId,park.name,park.point];
          //       this.sqliteHelperProvider.executeSql(sql,sql_params);
          //     });
          //   });
          })
          .then(()=>{
            this.userSettingProvider.setRefreshData();
          })
          .catch(err=>{
            console.log(err);
            reject(err)
          });
        }
      });
    });
  }

  /**
   * 从换缓存中读取数据
   */
  getParksFromCache(): Promise<any>{
    return this.sqliteHelperProvider.createOrOpenDb()
    .then(()=>{
      return this.sqliteHelperProvider.executeSql('SELECT * FROM parks_lite',
      []);
    });
  }


}
